package com.dotflat.dashboard.controller;

import com.dotflat.dashboard.service.DashboardService;
import com.dotflat.dashboard.util.PanelUtil;
import com.dotflat.dashboard.vo.*;
import com.matt.commons.dto.sso.AreaDTO;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.model.StatusResponse;
import com.matt.domain.Children;
import com.matt.domain.TargetObject;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.utils.DateUtil;
import com.matt.service.ChildrenService;
import com.matt.service.remoteCall.DTO.AreaStaffDTO;
import com.matt.service.remoteCall.DTO.SsoAreaDTO;
import com.matt.service.remoteCall.SsoCallService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.transaction.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static com.matt.foundation.constant.RequestConstant.TICKET;

@RestController
@RequestMapping("/v2/dashboard")
@Slf4j
@Api(tags = "看板")
public class DashboardController
{

    @Autowired
    private ChildrenService childrenService;

    @Autowired
    protected MemVerificationCache cache;

    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private DashboardService dashboardService;

    @ApiOperation(value = "大屏数据(生日，在园，缺勤)")
    @PostMapping("/dashboard_1")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK"),
    })
    @Transactional(rollbackOn = RuntimeException.class)
    public StatusResponse updateChild(@RequestHeader(TICKET) String ticket,String  classesId){
        StaffDTO staffDTO = cache.getStaff(ticket);
        if (Objects.isNull(staffDTO)){
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        if (Objects.isNull(classesId)){
            classesId= "";
        }
        String date = DateUtil.formatDateToStr(new Date());
        //生日，在园，缺勤
        List<Children> birthdays = childrenService.birthdays(staffDTO.getAreaId(),classesId);
        List<Children> inAreas = childrenService.getCheckStatus(staffDTO.getAreaId(),"1", date,classesId);
        List<Children> absense = childrenService.getCheckStatus(staffDTO.getAreaId(),"-1", date,classesId);

        Map map = new HashMap();
        map.put("birthdays",birthdays);
        map.put("inAreas",inAreas);
        map.put("absense",absense);
        return StatusResponse.success(map);
    }


    @ApiOperation(value = "大屏数据(综合信息，地区分布，年纪分布，幼儿分布，教师分布)")
    @PostMapping("/dashboard_2")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK"),
    })
    @Transactional(rollbackOn = RuntimeException.class)
    public StatusResponse dashboard_2(@RequestHeader(TICKET) String ticket){
        //集团下所有园区
        List<SsoAreaDTO> areaDTOList =  ssoCallService.getGroupAllArea( ticket);
        //集团下所有用户园区关联
        List<AreaStaffDTO> areaStaffList =  ssoCallService.getStaffAreaList( ticket);

        List<String> list = areaDTOList.stream().map(k->k.getId()).collect(Collectors.toList());
        String[] areaIds = list.toArray(new String[list.size()]);
        //总集团园学生
        List<Children>  childrenList = dashboardService.findAllByStatusAndAreaIdIn(1,areaIds);

        //综合信息对象
        InformationVO information  = dashboardService.information(areaDTOList);
        information.setTeacherCount(areaStaffList.size());
        information.setStaffCount(areaStaffList.size());

        //教师、教职工分布
        List<StaffCountVO> staffCountVOList = PanelUtil.getStaffCountVO(areaDTOList,areaStaffList,information.getStaffCount());

        //幼儿分布
        List<ChildrenCountVO> childrenCountVOList = PanelUtil.getChildrenCountVO(areaDTOList,childrenList,information.getChildrenCount());

        //年级分布
        List<GradeCountVO>  gradeCountVOList = dashboardService.grade(list);

        //集团 - 园区的班级总数
        List<Map>  list1 = dashboardService.getAreaIdCountList(list);

        //地区分布
        List<Map>  list2 = PanelUtil.getAreaCount(areaDTOList,list1,childrenCountVOList,staffCountVOList);

        Map map = new HashMap();
        //综合信息对象
        map.put("information",information);
        //教师、教职工分布
        map.put("staffCount",staffCountVOList);
        //幼儿分布
        map.put("childrenCount",childrenCountVOList);
        //年级分布
        map.put("gradeCount",gradeCountVOList);
        //年级分布
        map.put("areaCount",list2);

        return StatusResponse.success(map);
    }


    @ApiOperation(value = "集团数据统计 - 综合详细 - 班级分布)")
    @PostMapping("/dashboard_3")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK"),
    })
    @Transactional(rollbackOn = RuntimeException.class)
    public StatusResponse dashboard_3(@RequestHeader(TICKET) String ticket){

        //集团下所有园区
        List<SsoAreaDTO> areaDTOList =  ssoCallService.getGroupAllArea( ticket);

        List<String> list = areaDTOList.stream().map(k->k.getId()).collect(Collectors.toList());

        //集团 - 班级object 的集团数量
        List<ClassesCountVO> list2 = dashboardService.getClassCount(list);
        //查询班级object > 0 的集合
        List<TargetObject>  list1  = dashboardService.getAll();

        List<ClassesCountVO> list3 = new ArrayList<>();

        for (int i = 0; i < areaDTOList.size(); i++) {
            for (int j = 0; j < list1.size(); j++) {
                ClassesCountVO classesCountVO = new ClassesCountVO();
                classesCountVO.setAreaId(areaDTOList.get(i).getId());
                classesCountVO.setAreaName(areaDTOList.get(i).getAreaName());
                classesCountVO.setName(list1.get(j).getName());
                classesCountVO.setId(list1.get(j).getId());
                for (int k = 0; k < list2.size(); k++) {
                    if (StringUtils.equals(list2.get(k).getAreaId(),areaDTOList.get(i).getId()) &&
                            StringUtils.equals(list1.get(j).getId(),list2.get(k).getId()) ){
                        classesCountVO.setChildrenCount(list2.get(k).getChildrenCount());
                    }
                }
                list3.add(classesCountVO);
            }
        }

        int count = 0;
        List<ClassObjectCountVO> list4 = new ArrayList<>();
        for (int i = 0; i < list1.size(); i++) {
            ClassObjectCountVO classObjectCountVO = new ClassObjectCountVO();
            classObjectCountVO.setName(list1.get(i).getName());
            classObjectCountVO.setId(list1.get(i).getId());
            int childrenCount = 0;
            for (int k = 0; k < list2.size(); k++) {
                if (StringUtils.equals(list1.get(i).getId(),list2.get(k).getId()) ){
                    childrenCount += list2.get(k).getChildrenCount();
                }
            }
            count += childrenCount;
            classObjectCountVO.setChildrenCount(childrenCount);
            list4.add(classObjectCountVO);
        }

        Map map = new HashMap();
        //集团学生总数
        map.put("count",count);
        //班级object总数
        map.put("classObjectCount",list4);
        //园区班级object总数
        map.put("ClassesCount",list3);
        return StatusResponse.success(map);
    }



    @ApiOperation(value = "集团数据统计 - 综合详细 -  运营态势)")
    @PostMapping("/dashboard_4")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK"),
    })
    @Transactional(rollbackOn = RuntimeException.class)
    public StatusResponse dashboard_4(@RequestHeader(TICKET) String ticket){
        //集团下所有园区
        List<SsoAreaDTO> areaDTOList =  ssoCallService.getGroupAllArea( ticket);

        List<String> list = areaDTOList.stream().map(k->k.getId()).collect(Collectors.toList());
        //总集团园学生
        List<Map>  childrenList = dashboardService.getAreaIdChildrenCount(list);
        //集团在园总数
        int  inGarden = 0;
        //集团缺勤总数
        int lack = 0;
        List<ChildrenStateCountVO> childrenCountVOList = new ArrayList<>();
        for (int i = 0; i < areaDTOList.size(); i++) {
            ChildrenStateCountVO childrenCountVO = new ChildrenStateCountVO();
            childrenCountVO.setAreaId(areaDTOList.get(i).getId());
            childrenCountVO.setAreaName(areaDTOList.get(i).getAreaName());
            //在园的数量
            int inGardenCount = 0 ;
            //缺勤的数量
            int lackCount = 0;
            for (int j = 0; j < childrenList.size(); j++) {
                if (StringUtils.equals(childrenCountVO.getAreaId(),String.valueOf(childrenList.get(j).get("areaId")))){

                    if (StringUtils.equals("1",String.valueOf(childrenList.get(j).get("checkStatus"))) &&
                            StringUtils.equals(DateUtil.formatDayToStr(new Date()),String.valueOf(childrenList.get(j).get("checkTime")).substring(0,10))){
                        //在园的数量
                        inGardenCount++;
                    }else {
                        //缺勤的数量
                        lackCount++;
                    }
                }
            }
            inGarden += inGardenCount;
            lack += lackCount;

            childrenCountVO.setInGardenCount(inGardenCount);
            childrenCountVO.setLackCount(lackCount);
            childrenCountVOList.add(childrenCountVO);
        }

        Map map = new HashMap();
        map.put("inGardenCount",inGarden);
        map.put("lackCount",lack);
        map.put("areaCount",childrenCountVOList);
        return StatusResponse.success(map);
    }



    @ApiOperation(value = "园区数据统计 - 班级,人员统计")
    @PostMapping("/area_1")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK"),
    })
    @Transactional(rollbackOn = RuntimeException.class)
    public StatusResponse area_1(@RequestHeader(TICKET) String ticket){

        String areaId =  cache.getAreaId( ticket);

        //园区集合
        AreaClassListVO areaClassListVO = dashboardService.getAreaClass(areaId);
        return StatusResponse.success(areaClassListVO);
    }



    @ApiOperation(value = "园区大屏数据(综合信息，地区分布，年纪分布，幼儿分布，教师分布)")
    @PostMapping("/area_2")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK"),
    })
    @Transactional(rollbackOn = RuntimeException.class)
    public StatusResponse area_2(@RequestHeader(TICKET) String ticket){
        //集团下所有园区
        StaffDTO staffDTO =  ssoCallService.getStaffDTO( ticket);

        AreaDTO areaDTO =  ssoCallService.getAreaDTO( ticket);
        //集团下所有园区
        List<SsoAreaDTO> areaDTOList =  new ArrayList<>();
        SsoAreaDTO ssoAreaDTO = new SsoAreaDTO();
        ssoAreaDTO.setId(areaDTO.getId());
        ssoAreaDTO.setAreaName(areaDTO.getName());
        areaDTOList.add(ssoAreaDTO);

        //园区
        List<String> list = new ArrayList<>();
        list.add(areaDTO.getId());

        //集团下所有用户园区关联
        List<AreaStaffDTO> areaStaffList =  ssoCallService.getStaffAreaList( ticket);

        String[] areaIds = new  String[]{staffDTO.getAreaId()};
        //总集团园学生
        List<Children>  childrenList = dashboardService.findAllByStatusAndAreaIdIn(1,areaIds);

        //综合信息对象
        InformationVO information  = dashboardService.information(areaDTOList);
        int  staffCount  = 0 ;
        for (int i = 0; i < areaStaffList.size(); i++) {
            if (StringUtils.equals( areaStaffList.get(i).getAreaId(),staffDTO.getAreaId())){
                staffCount++;
            }
        }
        information.setTeacherCount(staffCount);
        information.setStaffCount(staffCount);

        //教师、教职工分布
        List<StaffCountVO> staffCountVOList = PanelUtil.getStaffCountVO(areaDTOList,areaStaffList,information.getStaffCount());

        //幼儿分布
        List<ChildrenCountVO> childrenCountVOList = PanelUtil.getChildrenCountVO(areaDTOList,childrenList,information.getChildrenCount());

        //年级分布
        List<GradeCountVO>  gradeCountVOList = dashboardService.grade(list);

        //集团 - 园区的班级总数
        List<Map>  list1 = dashboardService.getAreaIdCountList(list);

        //地区分布
        List<Map>  list2 = PanelUtil.getAreaCount(areaDTOList,list1,childrenCountVOList,staffCountVOList);

        Map map = new HashMap();
        //综合信息对象
        map.put("information",information);
        //教师、教职工分布
        map.put("staffCount",staffCountVOList);
        //幼儿分布
        map.put("childrenCount",childrenCountVOList);
        //年级分布
        map.put("gradeCount",gradeCountVOList);
        //年级分布
        map.put("areaCount",list2);

        return StatusResponse.success(map);
    }

}
